import { Component, OnInit } from '@angular/core';
import {StorageService} from "../../services/storage.service"; //引入一个服务

@Component({
  selector: 'app-todolist',
  templateUrl: './todolist.component.html',
  styleUrls: ['./todolist.component.css']
})
export class TodolistComponent implements OnInit {
  //storage=new StorageService() //创造一个storage对象   //官方不推荐

  public username:any;
  public list:any=[];

  constructor(private storage:StorageService) { //构造器
    //console.log(this.storage)
    this.storage.setItem('username',"zhangsan1")
  }

  ngOnInit(): void {
    this.username="zhangsan";
    this.list=this.storage.getItem('list')
  }
  getusername(){
    console.log(this.username) //通过双向数据绑定获取新的值
  }
  addusername(e:any){
    if (e.keyCode==13){
      this.list=this.storage.getItem("list")
      let status=false
      if (this.username=='zhangsan'){
        status=true
      }
      var obj={
        username:this.username,
        status:status,
      }
      console.log(obj)
      if (this.list){
        this.list.push(obj)
        this.storage.setItem("list",this.list)
      }else {
        console.log('kong')
        this.list=[]
        this.list.push(obj)
        this.storage.setItem("list",this.list)
      }
      console.log(this.list)
    }
  }
  deleteItem(id:any){
    this.list.splice(id,1)
    console.log(this.list)
    this.storage.setItem('list',this.list)  //每次修改list列表都要另行存储
  }
  changeData(key:any){
    this.list[key].status=!this.list[key].status
    this.storage.setItem('list',this.list) //每次修改list列表都要另行存储
  }
}
